package com.gao.mybatis.parse;

import com.gao.mybatis.configuration.Configuration;
import com.gao.mybatis.resource.ClassPathResources;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Element;

import java.util.List;
import java.util.Properties;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-03-28 22:04
 */
public class SqlMapperConfigXmlParser extends XmlParser {


    public SqlMapperConfigXmlParser(Configuration configuration) {
       super(configuration);
    }
    @Override
    Configuration doParse(Element rootElement,Configuration configuration) throws Exception {
        //解析Configuration
        List<Element> environmentEnvironmentList = rootElement.elements("environments");
        Properties properties = new Properties();
        for (Element ele : environmentEnvironmentList) {
            List<Element>  environments = ele.elements("environment");

            for (Element environment : environments) {
                List<Element> dataSources = environment.elements();
                for (Element dataSource : dataSources) {
                    List<Element> propertyList = dataSource.elements();
                    for (Element property : propertyList) {
                        properties.setProperty(property.attributeValue("name"), property.attributeValue("value"));
                    }
                }
            }
        }
        ComboPooledDataSource ds = new ComboPooledDataSource();

        ds.setDriverClass(properties.getProperty("driver"));
        ds.setJdbcUrl(properties.getProperty("url"));
        ds.setUser(properties.getProperty("username"));
        ds.setPassword(properties.getProperty("password"));
        configuration.setDataSource(ds);
        // 解析MappedStatement
        List<Element> environmentMapperList = rootElement.elements("mappers");
        for (Element element : environmentMapperList) {
            List<Element>  mappers = element.elements("mapper");
                for (Element o : mappers) {
                    MapperXmlParser mapperXmlParser = new MapperXmlParser(configuration);
                    String resource = o.attributeValue("resource");
                    mapperXmlParser.parse(new ClassPathResources(resource).getInputStream());
                }

        }
        return configuration;
    }
}
